Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
JavaScript Range setStart not working on "Bold" Text

I want to set cursor/caret position manually. This is working fine if contents are only text in a contenteditable. But if content contains text with bold, underline etc then the it is not working and it throws and error

Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset 2.

in below sample if you enter "0" in Node number then the cursor moves. But if you enter "1" in Node number then it throws error. What's wrong in it to move cursor over bold text.

  button.onclick = () => {
    let range = new Range();

    range.setStart(p.childNodes[node.value], start.value);
  
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(range);
  };
<p id="p" contenteditable="true">This is <b>bold</b></p>

Cursor Position <input id="start" type="number" value="2">  Node number <input id="node" type="number" value="0">
<button id="button">Mover Cursor</button>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In your example, p.childNodes[1] resolves to the node <b>bold</b>. You can only jump to the start or end of its text (index 0 and 1), as you are viewing the node as a whole. If you want to set the cursor within this node, you have to access its actual textual contents.

While not working for more complex cases, this should push you in the right direction:

let childNode = p.childNodes[node.value];
while (childNode.hasChildNodes()) {
  childNode = childNode.firstChild;
}
    
range.setStart(childNode, start.value);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda